package com.meizhuang.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.base.Strings;
import com.meizhuang.base.BaseController;
import com.meizhuang.entity.*;
import com.meizhuang.result.JsonResult;
import com.meizhuang.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping(value = "coin")
public class CoinController extends BaseController {

    @Autowired
    private UserCoinService userCoinService;

    @Autowired
    private WinningRecordService winningRecordService;

    @Autowired
    private CoinService coinService;
    @Autowired
    private UserIntegralService userIntegralService;

    @Autowired
    private UserIntegralRecordService userIntegralRecordService;

    /**
     * 金币列表
     * @return
     */
    @RequestMapping("/list")
    public JsonResult list(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new LinkedHashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        List<Coin> coins = coinService.selectAll();
        retMap.put("coins",coins);

        EntityWrapper<UserCoin> userCoinEntityWrapper= new EntityWrapper<>();
        userCoinEntityWrapper.eq("uid",userSession);
        List<UserCoin> userCoins = userCoinService.selectList(userCoinEntityWrapper);
        retMap.put("userCoins",userCoins);

        return JsonResult.buildSuccess(retMap);
    }

    /**
     * 添加金币 签到
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/add")
    public JsonResult add(HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> retMap = new LinkedHashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        String coinId = request.getParameter("coin_id");
        String quota = request.getParameter("quota");
        String lotteryNum = request.getParameter("lottery_num");

        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            EntityWrapper<UserCoin> userCoinEntityWrapper= new EntityWrapper<>();

            userCoinEntityWrapper.eq("uid",userSession);
            userCoinEntityWrapper.eq("coin_id",coinId);

            UserCoin userCoin = userCoinService.selectOne(userCoinEntityWrapper);

            if(null ==userCoin) {
                userCoin = new UserCoin();
                userCoin.setCoinId(Integer.parseInt(coinId));
                userCoin.setSource(Strings.nullToEmpty(request.getParameter("source")));
                userCoin.setQuota(Integer.parseInt(quota));
                userCoin.setCreateTime(new Date());
                userCoin.setUid(userSession);
                userCoin.setUpdateTime(userCoin.getCreateTime());
                userCoin.setLotteryNum(0);
                userCoinService.insert(userCoin);
            }else{
                userCoin.setQuota(userCoin.getQuota()+ Integer.parseInt(quota) );

                if(!StringUtils.isEmpty(lotteryNum)){

                    userCoin.setLotteryNum(Integer.parseInt(lotteryNum));
                }
                userCoinService.updateById(userCoin);
            }

            EntityWrapper<UserIntegral> userIntegralEntityWrapper = new EntityWrapper<UserIntegral>();
            userIntegralEntityWrapper.eq("uid", userSession);
            UserIntegral userIntegral = userIntegralService.selectOne(userIntegralEntityWrapper);

            if(null == userIntegral ){
                userIntegral = new UserIntegral();
                userIntegral.setUid(userSession);
                userIntegral.setQuota(10);
                userIntegral.setCreateTime(new Date());
                userIntegral.setUpdateTime(userIntegral.getCreateTime());
                userIntegralService.insert(userIntegral);
            }else{
                userIntegral.setQuota(userIntegral.getQuota()+10);
                userIntegral.setUpdateTime(new Date());
                userIntegralService.updateById(userIntegral);
            }

            UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
            userIntegralRecord.setUid(userSession);
            userIntegralRecord.setQuota(10);
            userIntegralRecord.setCreateTime(new Date());
            userIntegralRecord.setUpdateTime(userIntegralRecord.getCreateTime());
            userIntegralRecord.setSource("签到");
            userIntegralRecordService.insert(userIntegralRecord);

        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }

        return JsonResult.buildSuccess(retMap);
    }

    /**
     * 抽奖记录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/record")
    public JsonResult record(HttpServletRequest request, HttpServletResponse response) {

        Map<String,Object> retMap = new LinkedHashMap<>();

        Integer userSession = (Integer)super.getSession().getAttribute(UserInfo.USER_SESSION_UID);
        if(userSession == null){
            retMap.put("msg", "请登录");
            return JsonResult.buildError(retMap);
        }

        Lock lock = new ReentrantLock();
        try {
            lock.lock();

            String coinId = request.getParameter("coin_id");

            if(StringUtils.isEmpty(coinId)){
                retMap.put("msg", "请输入金币ID");
                return JsonResult.buildError(retMap);
            }

            //保存抽奖记录
            WinningRecord winningRecord = new WinningRecord();
            winningRecord.setCoinId(Integer.parseInt(coinId));
            winningRecord.setCreateTime(new Date());
            winningRecord.setUid(userSession);
            winningRecord.setUpdateTime(winningRecord.getCreateTime());

            winningRecordService.insert(winningRecord);
        }catch (Exception e){
            retMap.put("msg", e.getMessage());
            return JsonResult.buildError(retMap);
        }finally {
            lock.unlock();
        }
        return JsonResult.buildSuccess(retMap);
    }
}
